
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(int argc, char *argv[]) {
 if (argc != 2) {
        fprintf(stderr, "Usage: %s <hostname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    const char *hostname = argv[1];
    struct addrinfo hints, *result, *rp;
    int status;

    // 设置addrinfo结构体的参数
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;    // 支持IPv4或IPv6
    hints.ai_socktype = SOCK_STREAM; // 使用流式套接字

    // 获取addrinfo结构体链表
    if ((status = getaddrinfo(hostname, NULL, &hints, &result)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
        exit(EXIT_FAILURE);
    }

    // 遍历结果链表并打印IP地址
    for (rp = result; rp != NULL; rp = rp->ai_next) {
        void *addr;
        char ipstr[INET6_ADDRSTRLEN];

        if (rp->ai_family == AF_INET) { // IPv4
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)rp->ai_addr;
            addr = &(ipv4->sin_addr);
        } else { // IPv6
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)rp->ai_addr;
            addr = &(ipv6->sin6_addr);
        }

        // 将IP地址转换为字符串形式
        inet_ntop(rp->ai_family, addr, ipstr, sizeof(ipstr));
        printf("IP Address: %s\n", ipstr);
    }

    freeaddrinfo(result); // 释放addrinfo结构体链表的内存

    return 0;

}
